package com.leetcode.Offer;

import java.util.Arrays;
import java.util.TreeSet;

public class JZ40 {
    public int[] getLeastNumbers(int[] arr, int k) {

        Arrays.sort(arr);
        int[] ints = new int[k];
        System.arraycopy(arr, 0, ints, 0, k);
        return ints;
    }

    public int[] getLeastNumbers2(int[] arr, int k) {
        if (k < 1) {
            return new int[]{};
        }
        //容器法：不断把数据送入容器对比
        int[] ints = new int[k];//容器
        for (int i = 0; i < k; i++) {//容器初始化
            ints[i] = arr[i];
        }
        for (int i = k; i < arr.length; i++) {
            int[] index = toIndex(ints);
            if (arr[i] < index[1]) {
                ints[index[0]] = arr[i];
            }
        }
        return ints;

    }

    private int[] toIndex(int[] arr) {
        int[] ints = new int[2];//存储下标和最大值
        ints[1] = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > ints[1]) {
                ints[1] = arr[i];
                ints[0] = i;
            }
        }
        return ints;
    }
}
